package order.util;




import java.util.*;

public class SignUtil {
    public static final String APP_ID = "appId";
    public static final String APP_SECRET = "appSecret";
    public static final String NONCE = "nonce";
    public static final String TIMESTAMP = "timestamp";
    public static final String SIGN = "sign";

    /**
     * 获取签名
     *
     * @param paramMap  包含业务参数，appId,nonce,timestamp这3个公共参数
     * @param appSecret
     * @return
     */
    public static String getSign(Map<String, Object> paramMap, String appSecret) {
        String text = getUrlText(paramMap);
        text += "&appSecret=" + appSecret;
        return MD5SHA256Util.md5(text).toUpperCase();
    }

    private static String getUrlText(Map<String, Object> beanMap) {
        beanMap = getSortedMap(beanMap);
        StringBuilder builder = new StringBuilder();
        for (String key : beanMap.keySet()) {
            String value = beanMap.get(key).toString();
            builder.append(key);
            builder.append('=');
            builder.append(value);
            builder.append('&');
        }
        String text = builder.toString();
        return text.substring(0, text.length() - 1);
    }

    /**
     * 对普通map进行排序
     *
     * @param paramMap
     * @return
     */
    private static Map<String, Object> getSortedMap(Map<String, Object> paramMap) {
        SortedMap<String, Object> map = new TreeMap<String, Object>();
        for (String key : paramMap.keySet()) {
            if (key != null && !APP_SECRET.equals(key)) {
                Object value = paramMap.get(key);
                if (value != null) {
                    String valueStr = String.valueOf(value);
                    if (valueStr != null && !"".equals(valueStr)) {
                        map.put(key, value);
                    }
                }
            }
        }
        return map;
    }

    public static Map<String, Object> wrapMapParams(Map<String, Object> paramMap, String appId, String appSecret) {
        String nonce =  getUid();
        paramMap.put(APP_ID, appId);
        paramMap.put(TIMESTAMP, String.valueOf(System.currentTimeMillis()));
        paramMap.put(NONCE, nonce);
        String sign =SignUtil.getSign(paramMap, appSecret);
        paramMap.put(SIGN, sign);
        return new HashMap<>(paramMap);
    }
    public static String getUid() {
        UUID uuid = UUID.randomUUID();
        String guid = uuid.toString();
        guid = guid.replace("-", "");
        return guid;
    }
}